﻿using System;
using System.Linq;
using System.Web.Mvc;
using VideoSeller.Business.Data;
using VideoSeller.Business.Data.Enums;
using VideoSeller.Business.Models;
using VideoSeller.Core.Interfaces;
using VideoSeller.Web.Models;

namespace VideoSeller.Web.Controllers
{
	[Authorize]
	public class CabinetController : BaseController
	{
		private readonly ClientModel _clientModel;
		private readonly OnlineContentModel _onlineContentModel;
		private readonly CountryModel _countryModel;
		private readonly WaitModel _waitModel;
		private readonly PostingModel _postingModel;
		private readonly IDatabaseSettingsProvider _databaseSettingsProvider;
        private readonly SettingsModel _settingsModel;

        public CabinetController(ClientModel clientModel, OnlineContentModel onlineContentModel, CountryModel countryModel, WaitModel waitModel, IDatabaseSettingsProvider databaseSettingsProvider, PostingModel postingModel, SettingsModel settingsModel)
		{
			_clientModel = clientModel;
			_onlineContentModel = onlineContentModel;
			_countryModel = countryModel;
			_waitModel = waitModel;
			_databaseSettingsProvider = databaseSettingsProvider;
			_postingModel = postingModel;
            _settingsModel = settingsModel;

		}

		[HttpGet]
		public ViewResult Personal()
		{
			var model = new PersonalViewModel();
			model.LoadPersonalData(CurrentClient, _countryModel.GetAll(), CurrentClient.UserId == CurrentMembershipUser.UserId);
			return View(model);
		}

		[HttpPost]
		public ActionResult Personal(PersonalViewModel model)
		{
			if (ModelState.IsValid)
			{
				var client = new Client
					{
						FirstName = model.FirstName,
						LastName = model.LastName,
						Birthday = model.BirthDate,
						Sex = model.Sex == Sex.Male,
						Address = model.Address,
                        About = model.About,
						HomeSiteUrl = model.HomePage,
						CountryId = model.SelectedCountryId > 0 ? model.SelectedCountryId : default(int?),
                        ShowToOther =
                        (model.sFirstName ? "Fn" : "")
                        + (model.sLastName ? "Ln" : "")
                        + (model.sLogin ? "Lo" : "")
                        + (model.sAddress ? "Ad" : "")
                        + (model.sBirthDate ? "Bd" : "")
					};

                if ((string.IsNullOrWhiteSpace(model.OldPassword) == false)&&(string.IsNullOrWhiteSpace(model.NewPassword)==false))
                {
                    System.Web.Security.MembershipUser msu = System.Web.Security.Membership.GetUser(CurrentClient.UserId);
                    if(msu!=null) msu.ChangePassword(model.OldPassword, model.NewPassword);
                }

				_clientModel.UpdateClient(client, CurrentClient.UserId);

				return RedirectToAction("Personal");
			}

			return View(model);
		}

		[HttpGet]
		public ViewResult Finance()
		{
            int ustvsl = 1;
			var model = new FinanceViewModel
				{
					PayPalMerchantId = _databaseSettingsProvider.PayPalMerchantId,
					PayPalEnvironment = _databaseSettingsProvider.PayPalEnvironment,
					PayPalCallbackUrl = _databaseSettingsProvider.PayPalCallbackUrl,
					UsdToVsl = ustvsl,
					UsdToVslDescription = _databaseSettingsProvider.UsdToVslDescription,
					Postings = CurrentClient.Finance.Postings.OrderByDescending(x => x.Date).ToList(),
					PersonalInfoRequired = _clientModel.IsPersonalInfoEmpty(CurrentClient.UserId),
                    NoManyForWithdrawal = (CurrentClient.Finance.Total / ustvsl) < _databaseSettingsProvider.WithdrawalMin
				};

			return View(model);
		}

		[HttpPost]
		public ActionResult MarkOnlineContent(int id)
		{
			_waitModel.MarkOnlineContent(id, CurrentClient.UserId);

			return RedirectToAction("Content", "Home", new {id});
		}

		[HttpGet]
		public ViewResult Online(int? page, int? pageSize)
		{
			var model = GetContentListViewModel(CurrentClient.UserId, OnlineContentType.Online, "Online", page, pageSize);
			return View(model);
		}

		[HttpGet]
		public ViewResult History(int? page, int? pageSize)
		{
			var model = GetContentListViewModel(CurrentClient.UserId, OnlineContentType.History, "History", page, pageSize);
			return View(model);
		}

		[NonAction]
		public ContentListViewModel GetContentListViewModel(Guid userId, OnlineContentType onlineContentType, string filterAction, int? page, int? pageSize)
		{
			var model = new ContentListViewModel { ShowRating = false,
                                                   ShowEditAction = true,
                                                   Items = _onlineContentModel.GetAll(userId, onlineContentType).OrderByDescending(x =>x.CreatedTime),
                                                   AllCamParams = _settingsModel.QualityStrings,
                                                   currentClient = CurrentClient,
                                                   WowzaPatch = _settingsModel.GetSetting("WowzaPath").Value
            };
            if (filterAction == "History")
                model.Items = model.Items.OrderByDescending(x => x.BroadcastStart);
			var filterModel = new ContentListFilterViewModel
			{
				Action = filterAction,
				Controller = "Cabinet",
				PageNumber = page.HasValue ? page.Value : 1,
				PageSize = pageSize.HasValue ? pageSize.Value : 10
			};

			var total = model.Items.Count();
			model.Items = model.Items.Skip((filterModel.PageNumber - 1) * filterModel.PageSize).Take(filterModel.PageSize);
			filterModel.PageCount = total / filterModel.PageSize;
			filterModel.Total = total;
			filterModel.Filter = new FilterViewModel();
			model.FilterViewModel = filterModel;

			return model;
		}

		[HttpPost]
		public ActionResult Withdraw(WithdrawViewModel model)
		{
			WithdrawType withdrawType;

			if (Enum.TryParse(model.WithdrawType, out withdrawType))
			{
				_postingModel.StartWithdraw(CurrentClient.Finance, withdrawType, withdrawType == WithdrawType.PayPal ? model.Email : model.Address);
			}

			return RedirectToAction("Finance");
		}
	}
}